package com.imachen.ymcc.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @description: 拦截feign调用拦截器
 * @author: AChen
 * @date: 2022/10/24 0024 : 13:05
 * @version: ver1.0
 * @email
 */
@Component
public class InterceptFeignInterceptor implements RequestInterceptor {

    //请求头中的token
    private final String AUTHORIZATION_HEADER = "Authorization";

    @Override
    public void apply(RequestTemplate requestTemplate) {
        //1.获取请求对象
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();

        //2.从请求头获取到令牌
        String token = request.getHeader(AUTHORIZATION_HEADER);
        if (!StringUtils.isEmpty(token)) {
            //3.把令牌添加到Feign的请求头
            requestTemplate.header(AUTHORIZATION_HEADER,token);
        }

    }
}
